<template>
  <view class="page">
    <view class="main padding-lr-sm">
      <!-- 主页面 -->
      <view class="margin-top" v-if="!answer">
        <up-text bold size="16" text="常见问题"></up-text>
        <up-text margin="10px 0 0 0" size="14" color="#666" text="1、孩子作业拖延怎么办？"
          @click="handleItemClick('孩子作业拖延怎么办?')"></up-text>
        <up-text margin="10px 0 0 0" size="14" color="#666" text="2、孩子动不动就发脾气，如何管理情绪？"
          @click="handleItemClick('孩子动不动就发脾气，如何管理情绪?')"></up-text>
        <up-text margin="10px 0 0 0" size="14" color="#666" text="3、孩子不想上兴趣班了，该坚持还是放弃？"
          @click="handleItemClick('孩子不想上兴趣班了，该坚持还是放弃?')"></up-text>
        <!-- 学习科普 和 健康 -->
        <!-- <view class="flex">
          <view class="flex-sub radius-lg text-center padding-sm study" hover-class="click"
            @click="handleItemClick('学习科普')">
            <image :src="IMAGE_URL +
              '/profile/content/2025/05/16/x3yzXE7wwVIxb899276e61942b7314e9c12d1948d057_20250516133911A011.png'
              " style="width: 120rpx" mode="widthFix"></image>
            <up-text color="#3D511D" text="学习科普" size="20" align="center"></up-text>
          </view>
          <view class="radius-lg text-center padding-sm health margin-left-sm" style="flex: 1.5" hover-class="click"
            @click="handleItemClick('健康')">
            <image :src="IMAGE_URL +
              '/profile/content/2025/05/16/slnEegnnFwyM4165ac5eefcf0b84b1da056d8352ae1d_20250516133842A010.png'
              " style="width: 120rpx" mode="widthFix"></image>
            <up-text color="#3D511D" text="健康" size="20" align="center"></up-text>
          </view>
        </view> -->
        <!-- 兴趣话题 -->
        <!-- <view class="hobby radius-lg margin-tb padding-lr-sm padding-tb" hover-class="click"
          @click="handleItemClick('兴趣话题')">
          <image src="/static/images/ai_icon_streamline_ai-science-spark.png" style="width: 90rpx" class="margin-lr"
            mode="widthFix"></image>
          <up-text color="#514721" text="兴趣话题" size="20" margin="20rpx 0 0 0"></up-text>
          <up-text color="#666" text="科技浪潮中，编程、科学实验、天文地理探索，为孩子打开科学世界大门" size="14"></up-text>
        </view> -->
        <!-- 比赛和营养搭配 -->
        <!-- <view class="flex">
          <view class="radius-lg text-center competition flex-sub" style="padding: 100rpx 0" hover-class="click"
            @click="handleItemClick('比赛话题')">
            <image src="/static/images/ai_icon_sword-fight.png" style="width: 120rpx" mode="widthFix"></image>
            <up-text color="#262661" text="比赛话题" size="20" align="center"></up-text>
          </view>
          <view class="flex-sub padding-sm radius-lg text-center nutrition margin-left-sm" style="padding: 100rpx 0"
            hover-class="click" @click="handleItemClick('营养搭配')">
            <image src="/static/images/icon_nutrition-outline.png" style="width: 120rpx" mode="widthFix"></image>
            <up-text color="#3D5718" text="营养搭配" size="20" align="center"></up-text>
          </view>
        </view> -->
      </view>

      <!-- 聊天页面 -->
      <view v-else class="chat-page">
        <view class="flex padding-lr-sm">
          <view class="ai-avatar">
            <image :src="IMAGE_URL +
              '/profile/content/2025/05/16/WXrU9dWZsMZp91ccbfbd150eacf22457e3854128603e_20250516133130A008.png'
              " style="width: 140rpx" mode="widthFix"></image>
          </view>
          <up-text size='12' align="right" text="重新提问" @click="clear"></up-text>
        </view>

        <view class="margin-lg">
          <up-text size="14" text="根据您的提问，" bold></up-text>
          <up-text size="14" text="自动为您生成————" bold></up-text>
        </view>
        <scroll-view scroll-y class="chat-content" :scroll-top="scrollTop" @scroll="scroll">
          <!-- <view
            v-for="(item, index) in chatList"
            :key="index"
            class="message-item ai-message"
          > -->
          <!-- <view class="margin-top"> -->
          <!-- <text class="text-gray text-sm">{{ item.content }}</text> -->
          <text class="text-gray text-sm">{{ answer }}</text>
          <!-- </view> -->
          <!-- </view> -->
        </scroll-view>
        <view></view>
      </view>
    </view>
    <!-- 底部输入框 -->
    <view class="footer padding-lr padding-tb-xs">
      <view class="input-box flex align-center">
        <up-icon name="/static/images/ai_icon_Typetalk.png" size="90rpx" color="#87C38F"></up-icon>
        <view class="margin-lr flex-sub">
          <up-input type="text" v-model="inputValue" placeholder="输入问题" border="none" @confirm="handleSend" />
        </view>
      </view>
      <view class="send-btn" hover-class="click" @click="handleSend">
        <up-icon name="/static/images/ai_icon_type.png" size="90rpx" color="#FFB800"></up-icon>
      </view>
      <!-- <view @click="toTop"> totop </view> -->
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { IMAGE_URL } from '@/utils/env';
const inputValue = ref(''); // 提问内容
const chatList = ref([{ type: 'ai', content: 'text' }]); //回复列表
const answer = ref('');
const scrollTop = ref(0);
const oldScrollTop = ref(0);
const isLoading = ref(false);
const handleItemClick = (topic) => {
  inputValue.value = topic;
  handleSend();
};

const handleSend = async () => {
  if (!inputValue.value.trim()) {
    uni.showToast({
      title: '请输入问题',
      icon: 'none'
    })
    return
  };
  uni.showLoading({
    title: 'AI思考中...'
  });
  let token = uni.getStorageSync('token');
  const requestTask = uni.request({
    url: 'https://api.banyatech.cn/stage-api/app/ai/streamChat',
    timeout: 600000,
    responseType: 'arraybuffer',
    enableChunked: true, // 配置这里,最重要
    method: 'POST',
    header: {
      Authorization: token,
      Accept: 'text/event-stream',
    },
    data: {
      inputs: {
        input: inputValue.value
      }
    },
    success: (res) => {
      console.log('Data received 数据接受完毕:', res)
      // uni.hideLoading()
    },
    fail: (error) => {
      console.log('打印***error 错误处理', error)
      // uni.hideLoading()
    },
    complete: (complete) => {
      console.log('打印***complete 完成接收', complete)
      // uni.hideLoading()
    }
  })

  // 处理数据
  requestTask.onChunkReceived((res) => {
    uni.hideLoading()
    toTop();
    // inputValue.value = '';
    answer.value = '';
    const uint8Array = new Uint8Array(res.data);
    const decoder = new TextDecoder('utf-8');
    const text = decoder.decode(uint8Array);
    const arr = text.split('\n\n').filter(Boolean)
    let jsonStr = ''
    arr.forEach(msg => {
      if (msg.startsWith('data:')) {
        jsonStr = msg.substring(5).trim(); // 去掉 'data:data: ' 前缀
        if (jsonStr.endsWith('event:message')) {
          jsonStr = jsonStr.substring(0, jsonStr.length - 'event:message'.length).trim();
        }
        try {
          const data = JSON.parse(jsonStr);
          switch (data.event) {
            case 'text_chunk': {
              // 拼接返回文本
              answer.value += data.data.text;
              break;
            }
            case 'message_end':
              // 消息结束
              break;
          }
        } catch (e) {
          // console.error('解析JSON失败：', e);
        }
      }
    });
  })
};

const toTop = () => {
  scrollTop.value = oldScrollTop.value;
  setTimeout(() => {
    scrollTop.value = 0;
  }, 100);
  console.log('success');
};
const scroll = (e) => {
  oldScrollTop.value = e.detail.scrollTop;
};
const clear = () => {
  console.log('clear');
  answer.value = '';
  inputValue.value = ''
}
</script>

<style lang="scss" scoped>
.page {
  background-color: #fff;
}

.study {
  background: #f5e9cf;
}

.health {
  background: #cff0e5;
}

.hobby {
  background: #f6e1db;
}

.competition {
  background: #ceceee;
  flex: 1.5;
}

.nutrition {
  background: #dfedca;
}

.input-box {
  background: #f5f5f5;
  border-radius: 50rpx;
  height: 90rpx;
  margin-right: 20rpx;
  flex: 1;

  input {
    height: 100%;
    font-size: 28rpx;
  }
}

.chat-page {
  background: #f8f9f3;
  position: relative;
  border-radius: 30rpx;

  // border: solid 1px red;
  .ai-avatar {
    // position: absolute;
    // top: -50%;
    // left: -50%;
    width: 140rpx;
    height: 140rpx;
    // border: solid 1px red;
  }

  .chat-content {
    padding: 20rpx 40rpx;
    box-sizing: border-box;
    height: 60vh;
    margin-top: 20rpx;
    // .message-item {
    //   margin-bottom: 30rpx;
    // }
  }
}
</style>
